//
//  MyNewSetViewController.m
//  EMMApp
//
//  Created by Mac on 16/6/29.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "MyNewSetViewController.h"

/** ViewController
 *
 *  ViewController导入.h文件
 */
#import "ModifyPasswordViewController.h"
#import "VPImageCropperViewController.h"
#import "VersionUpdateViewController.h"     //版本更新
#import "FeedbackViewController.h"          //反馈
#import "AboutViewController.h"             //关于

/** 系统库和第三方文件
 *
 *  导入.h文件
 */
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "NSString+Base64.h"
#import "NSData+Base64.h"

/** Api
 *
 *  Api调用导入.h文件
 */
#import "EditMemberInfoApi.h"
#import "LogoutApi.h"

/** Cell
 *
 *  Cell导入.h文件
 */
#import "MySetCell.h"

@interface MyNewSetViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,VPImageCropperDelegate,UITableViewDelegate,UITableViewDataSource>

/**
 *  创建UITableView 命名为：examineListTableView
 */
@property (nonatomic, strong) UITableView *examineListTableView;

/**
 *  创建UIImageView 头像
 */
@property (strong, nonatomic) UIImageView *portraitImageView;

@end

@implementation MyNewSetViewController

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNavigationController];
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    _examineListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight) style:UITableViewStylePlain];
    _examineListTableView.delegate = self;
    _examineListTableView.dataSource = self;
    _examineListTableView.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    _examineListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_examineListTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 生命周期函数调用
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

#pragma mark - 导航
- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"个人设置";
    [self configLeftBtn];
}

#pragma mark - UITableView 代理- UITableViewDelegate,UITableViewDataSource
/**
 *  功能描述：
 *  UITableView代理方法
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 11;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 110;
    } else if (indexPath.row == 5) {
        return 25;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellId = @"MySetCellId";
    MySetCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MySetCell" owner:self options:nil] lastObject];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.imagejtou.hidden = YES;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 52, 100, 20)];
        label.font = [UIFont systemFontOfSize:15];
        label.text = @"头像";
        label.textColor = [UIColor colorFromHexCode:@"#5A5A5A"];
        [cell addSubview:label];
        UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(EMM_WIDTH-22, 52, 12, 16)];
        im.image = [UIImage imageNamed:@"btn_qiaoj"];
        [cell addSubview:im];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 10)];
        imageView.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
        [cell addSubview:imageView];
        [cell addSubview:self.portraitImageView];
        [self loadPortrait];
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10.5, EMM_WIDTH, 0.5)];
        imageV.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageV];
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 109.5, EMM_WIDTH-10, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
    } else if (indexPath.row == 1) {
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-10, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
        cell.nameLabel.text = @"生日";
        cell.nameOneLabel.text = self.birthday;
        cell.imagejtou.hidden = YES;
    } else if (indexPath.row == 2) {
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-10, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
        cell.nameLabel.text = @"姓名";
        cell.nameOneLabel.text = self.name;
        cell.imagejtou.hidden = YES;
    } else if (indexPath.row == 3) {
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-10, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
        cell.nameLabel.text = @"入职时间";
        cell.nameOneLabel.text = self.entryTime;
        cell.imagejtou.hidden = YES;
    } else if (indexPath.row == 4) {
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49.5, EMM_WIDTH, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
        cell.nameLabel.text = @"密码";
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(EMM_WIDTH-125, 15, 100, 20)];
        label.font = [UIFont systemFontOfSize:15];
        label.text = @"点击可重置";
        label.textAlignment = NSTextAlignmentRight;
//        [cell addSubview:label];
//        cell.nameTextLabel.text = @"点击可重置";
    } else if (indexPath.row == 5) {
        cell.imagejtou.hidden = YES;
        cell.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    } else if (indexPath.row == 6) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 0.5)];
        imageView.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView];
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-10, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
        cell.nameLabel.text = @"反馈";
    } else if (indexPath.row == 7) {
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-10, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
        cell.nameLabel.text = @"版本说明";
    } else if (indexPath.row == 8) {
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49.5, EMM_WIDTH, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
        cell.nameLabel.text = @"关于";
    } else if (indexPath.row == 9) {
        cell.imagejtou.hidden = YES;
        cell.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    } else if (indexPath.row == 10) {
        cell.imagejtou.hidden = YES;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 0.5)];
        imageView.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, EMM_WIDTH - 20, 20)];
        label.text = @"退出登录";
        label.font = [UIFont systemFontOfSize:16];
        label.textAlignment = NSTextAlignmentCenter;
        [cell addSubview:label];
        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49.5, EMM_WIDTH, 0.5)];
        imageView1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
        [cell addSubview:imageView1];
    }
    return cell;
}

#pragma mark -UITableViewCell触发点击事件调用方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 4) {
        ModifyPasswordViewController *mvc = [[ModifyPasswordViewController alloc] init];
        [self.navigationController pushViewController:mvc animated:YES];
    }else if (indexPath.row == 6){
        FeedbackViewController *mvc = [[FeedbackViewController alloc] init];
        [self.navigationController pushViewController:mvc animated:YES];
        [mvc setFeedbackBlock:^{
            [self showToast:@"提交成功"];
        }];
    }else if (indexPath.row == 7){
        VersionUpdateViewController *mvc = [[VersionUpdateViewController alloc] init];
        [self.navigationController pushViewController:mvc animated:YES];
    }else if (indexPath.row == 8){
        AboutViewController *mvc = [[AboutViewController alloc] init];
        [self.navigationController pushViewController:mvc animated:YES];
    }else if (indexPath.row == 10) {
        [self OnLogOut];
    }
}

#pragma mark - 退出系统
- (void)OnLogOut {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认退出" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self creatUpExit];
    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark - 退出登录Api调用方法
/**
 *  功能描述：
 *  退出登录Api调用方法
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
- (void)creatUpExit {
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *merchantId = [userdf objectForKey:@"merchantId"];
    NSString *userId = [userdf objectForKey:@"userNameId"];
    NSString *token = [userdf objectForKey:@"is_login"];
    LogoutApi *api = [[LogoutApi alloc] initWithMerchantId:merchantId userId:userId token:token];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        LogoutApi *result = (LogoutApi *)request;
        if (result.isSuccess) {
            NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
            NSDictionary *dictionary = [defs dictionaryRepresentation];
            for(NSString *key in [dictionary allKeys]){
                if ([key isEqualToString:@"DeviceToken123"] ||
                    [key isEqualToString:@"loginText"] ||
                    [key isEqualToString:@"provinceCityDistrict"]) {
                } else {
                    [defs removeObjectForKey:key];
                    [defs synchronize];
                }
            }
            [appInstance showLogin];
        } else {
            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
            NSDictionary *dictionary = [defs dictionaryRepresentation];
            for(NSString *key in [dictionary allKeys]){
                if ([key isEqualToString:@"DeviceToken123"] || [key isEqualToString:@"loginText"] || [key isEqualToString:@"provinceCityDistrict"]) {
                    
                }else {
                    [defs removeObjectForKey:key];
                    [defs synchronize];
                }
            }
            [appInstance showLogin];
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
        NSDictionary *dictionary = [defs dictionaryRepresentation];
        for(NSString *key in [dictionary allKeys]){
            if ([key isEqualToString:@"DeviceToken123"] || [key isEqualToString:@"loginText"] || [key isEqualToString:@"provinceCityDistrict"]) {
                
            } else {
                [defs removeObjectForKey:key];
                [defs synchronize];
            }
        }
        [appInstance showLogin];
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - 修改头像
/**
 *  功能描述：
 *  异步加载头像
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
- (void)loadPortrait {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
        dispatch_sync(dispatch_get_main_queue(), ^{
            if ([_headPic isEqualToString:@""]) {
                self.portraitImageView.image = [UIImage imageNamed:@"touxiang"];
            } else {
                [_portraitImageView sd_setImageWithURL:[NSURL URLWithString:_headPic] placeholderImage:[UIImage imageNamed:@"touxiang"]];
            }
        });
    });
}

#pragma mark - 弹出修改头像选择框
/**
 *  功能描述：
 *  创建UIActionSheet弹出照片选择方式（相册，拍照）
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
/**
 *  功能描述：
 *  VPImageCropperDelegate代理方法
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
//选择完成返回代理事件
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    self.portraitImageView.image = editedImage;
    [self postImage:editedImage];
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}
//取消选择图片
- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
/**
 *  功能描述：
 *  UIActionSheet点击哪一个按钮事件
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            //设置使用后置摄像头，可以使用前置摄像头
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            [controller.navigationBar setBarTintColor:[UIColor whiteColor]];
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [controller.navigationBar setBarTintColor:[UIColor whiteColor]];            
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    viewController.navigationItem.rightBarButtonItem.tintColor = [UIColor orangeColor];
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark portraitImageView getter
/**
 *  功能描述：
 *  懒加载创建头像视图
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
- (UIImageView *)portraitImageView {
    if (!_portraitImageView) {
        _portraitImageView = [[UIImageView alloc] initWithFrame:CGRectMake(EMM_WIDTH-80-22, 20, 80, 80)];
        [_portraitImageView.layer setCornerRadius:(_portraitImageView.frame.size.height/2)];
        [_portraitImageView.layer setMasksToBounds:YES];
        [_portraitImageView setContentMode:UIViewContentModeScaleAspectFill];
        [_portraitImageView setClipsToBounds:YES];
        _portraitImageView.layer.shadowColor = [UIColor blackColor].CGColor;
        _portraitImageView.layer.shadowOffset = CGSizeMake(4, 4);
        _portraitImageView.layer.shadowOpacity = 0.5;
        _portraitImageView.layer.shadowRadius = 1.0;
        _portraitImageView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _portraitImageView.layer.borderWidth = 0.5f;
        _portraitImageView.userInteractionEnabled = YES;
        _portraitImageView.backgroundColor = [UIColor lightGrayColor];
        UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editPortrait)];
        [_portraitImageView addGestureRecognizer:portraitTap];
        
    }
    return _portraitImageView;
}
/**
 *  功能描述：
 *  将选择的图片转换成base64位数据
 *  更新时间：2016/12/22
 *  更新人：guowei
 */- (void)postImage:(UIImage *)portraitImg
{
    NSData* imageData = UIImageJPEGRepresentation(portraitImg, 0.1);
    
    if (imageData == NULL) {
        return;
    }
    NSString *base64EncodedString = [NSString base64StringFromData:imageData length:[imageData length]];
    
    NSString *encodedImageStr = base64EncodedString;
    NSLog(@"%@",encodedImageStr);
    [self postEditMemberInfoApiHeadPic:encodedImageStr];
}

#pragma mark - 修改头像Api
/**
 *  功能描述：
 *  上传头像接口Api
 *  更新时间：2016/12/22
 *  更新人：guowei
 */
- (void)postEditMemberInfoApiHeadPic:(NSString *)headPic {
    EditMemberInfoApi *api = [[EditMemberInfoApi alloc] initWithHeadPic:headPic headType:@".png"];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        EditMemberInfoApi *result = (EditMemberInfoApi *)request;
        if (result.isSuccess) {
            
        } else {
            [self showToast:result.resultData.errorMsg];
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

@end
